<template>
  <div class="app-container">
    <el-button type="primary" @click="handleAddRole" icon="el-icon-circle-plus-outline">添加用户</el-button>

    <el-table :data="adminList" style="width: 100%;margin-top:30px;" border>
      <el-table-column align="center" label="编号" width="50">
        <template slot-scope="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="头像" width="120">
        <template slot-scope="scope">
          <img :src="scope.row.avatarUrl"  min-width="70" height="70" />
        </template>
      </el-table-column>

      <el-table-column align="center" label="管理员名" width="110">
        <template slot-scope="scope">
          <a @click="handleEdit(scope)"> {{ scope.row.adminName }}</a>
        </template>
      </el-table-column>

      <el-table-column align="center" label="真实姓名" width="110">
        <template slot-scope="scope">
          {{ scope.row.realName }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="联系方式"  width="140">
        <template slot-scope="scope">
          {{ scope.row.phone }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="添加时间"  width="180">
        <template slot-scope="scope">
          <i class="el-icon-time" />
          {{ timestampToTime(scope.row.gmtCreate) }}
        </template>
      </el-table-column>

      <el-table-column align="header-center" label="描述">
        <template slot-scope="scope">
          {{ scope.row.remark }}
        </template>
      </el-table-column>

      <el-table-column align="center" label="操作" width="200">
        <template slot-scope="scope">
          <el-button type="primary" size="small" @click="handleEdit(scope) " icon="el-icon-edit">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope)" icon="el-icon-delete">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :visible.sync="dialogVisible" :title="dialogType==='edit'?'编辑管理员信息':'添加管理员'">
      <el-form ref="admin" :model="admin" :rules="commitRules" label-width="80px" label-position="left">
<!--        <el-button type="primary" size="small" icon="el-icon-upload">上传头像</el-button>-->
        <el-form-item label="管理员名" prop='adminName'>
          <input v-model="admin.id" type="hidden"/>
          <el-input v-model="admin.adminName" placeholder="请输入管理员名 （字母开头，5到16位，支持字母，数字，下滑线，减号）" />
        </el-form-item>
        <el-form-item label="密码" prop='password'>
          <el-input type="password" v-model="admin.password" placeholder="请输入管理员密码 （至少六位）" />
        </el-form-item>
        <el-form-item v-if="isShowConfirmPassword" label="确认密码" prop='confirmPassword'>
          <el-input type="password" v-model="admin.confirmPassword" placeholder="请再次输入管理员密码" />
        </el-form-item>
        <el-form-item label="真实姓名" prop='realName'>
          <el-input v-model="admin.realName" placeholder="请输入管理员真实姓名" />
        </el-form-item>
        <el-form-item label="联系方式" prop='phone'>
          <el-input v-model="admin.phone" placeholder="请输入管理员联系方式" />
        </el-form-item>
        <el-form-item label="备注" prop='remark'>
          <el-input
            v-model="admin.remark"
            :autosize="{ minRows: 2, maxRows: 4}"
            type="textarea"
            placeholder="请填写管理员备注"
          />
        </el-form-item>
      </el-form>
      <div style="text-align:right;">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmAdmin">提交</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { validateUserName, validatePhoneTwo, validateRealName } from '@/utils/validate'
import { getAllAdmin, add, update, remove } from '@/api/user'

const defaultAdmin = {
  id: null,
  adminName: '',
  password: '',
  confirmPassword: '',
  permission: '',
  phone: '',
  realName: '',
  remark: '',
  token: '',
  avatarUrl: '',
  gmtCreate: '',
  gmtModify: ''
}

export default {
  // 数据
  data() {
    // 以下都是验证规则
    const validAdminName = (rule, value, callback) => {
      if (value == '' || value == undefined || value == null) {
        callback(new Error('请填写管理员名！'))
      } else if (!validateUserName(value)) {
        callback(new Error('管理员名格式错误！'))
      } else {
        callback()
      }
    }
    const validPassword = (rule, value, callback) => {
      this.isShowConfirmPassword = true
      if (value == '' || value == undefined || value == null) {
        callback(new Error('请填写管理员密码！'))
      } else if (value.length < 6) {
        callback(new Error('密码不能小于6位！'))
      } else {
        callback()
      }
    }
    const validConfirmPassword = (rule, value, callback) => {
      if (value == '' || value == undefined || value == null) {
        callback(new Error('请再次填写密码！'))
      } else if (value.length < 6 || value != this.admin.password) {
        callback(new Error('两次密码不相同！'))
      } else {
        callback()
      }
    }
    const validRealName = (rule, value, callback) => {
      if (value == '' || value == undefined || value == null) {
        callback(new Error('请填写管理员真实是姓名！'))
      } else if (!validateRealName(value)) {
        callback(new Error('管理员真实姓名格式不正确！'))
      } else {
        callback()
      }
    }
    const validPhone = (rule, value, callback) => {
      if (value == '' || value == undefined || value == null) {
        callback(new Error('请填写管理员联系方式！'))
      } else if (!validatePhoneTwo(value)) {
        callback(new Error('电话号码格式不正确！'))
      } else {
        callback()
      }
    }
    return {
      admin: Object.assign({}, defaultAdmin),
      commitRules: {
        adminName: [{ required: true, trigger: 'blur', validator: validAdminName }],
        password: [{ required: true, trigger: 'blur', validator: validPassword }],
        confirmPassword: [{ required: true, trigger: 'blur', validator: validConfirmPassword }],
        realName: [{ required: true, trigger: 'blur', validator: validRealName }],
        phone: [{ required: true, trigger: 'blur', validator: validPhone }]
      },
      routes: [],
      adminList: [],
      avatarList: ['https://cdn.jsdelivr.net/gh/fly-liuhao/ImageHosting/Img/12.jpg',
        'https://cdn.jsdelivr.net/gh/fly-liuhao/ImageHosting/Img/img-bc5c6319a79621604967eca293795e34.jpg',
        'https://cdn.jsdelivr.net/gh/fly-liuhao/ImageHosting/Img/1582260894582.jpeg',
        'https://cdn.jsdelivr.net/gh/fly-liuhao/ImageHosting/Img/1576041146435.jpeg',
        'https://cdn.jsdelivr.net/gh/fly-liuhao/ImageHosting/Img/1582260605789.jpeg'],
      dialogVisible: false,
      dialogType: 'new',
      checkStrictly: false,
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      isShowConfirmPassword: true
    }
  },

  // 钩子生命函数
  created() {
    this.getAdmins()
  },

  // 方法
  methods: {

    async getAdmins() {
      const res = await getAllAdmin()
      console.log(res)
      this.adminList = res.data
    },
    generateArr(routes) {
      let data = []
      routes.forEach(route => {
        data.push(route)
        if (route.children) {
          const temp = this.generateArr(route.children)
          if (temp.length > 0) {
            data = [...data, ...temp]
          }
        }
      })
      return data
    },
    // 点击新加管理员
    handleAddRole() {
      this.isShowConfirmPassword = true
      this.admin = Object.assign({}, defaultAdmin)
      this.dialogType = 'new'
      this.dialogVisible = true
      // 清除添加时的验证提示
      this.$refs['admin'].clearValidate()
    },
    // 点击编辑管理员
    handleEdit(scope) {
      this.isShowConfirmPassword = false
      this.admin = Object.assign({}, scope.row)
      this.dialogType = 'edit'
      this.dialogVisible = true
      this.checkStrictly = true
      // 清除添加时的验证提示
      this.$refs['admin'].clearValidate()
    },
    // 删除管理员
    handleDelete({ $index, row }) {
      this.$confirm('真的要删除该管理员吗?', 'Warning', {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        const res = await remove(row.id)
        const result = res.data
        if (result === true) {
          this.adminList.splice($index, 1)
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
        } else {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        }
      }).catch(err => {
        console.error(err)
      })
    },
    // 提交信息
    confirmAdmin() {
      this.$refs.admin.validate(async valid => {
        if (valid) {
          // 判断新增还是修改的提交
          const isEdit = this.dialogType === 'edit'
          // 修改管理员信息
          if (isEdit) {
            const { data } = await update(this.admin)
            if (data === true) {
              for (let index = 0; index < this.adminList.length; index++) {
                if (this.adminList[index].id === this.admin.id) {
                  this.adminList.splice(index, 1, Object.assign({}, this.admin))
                  break
                }
              }
            }
          } else {
            // 添加管理员
            // 设置创建时间以及修改时间
            this.admin.gmtCreate = this.admin.gmtModify = (new Date()).getTime()
            // 设置头像
            this.admin.avatarUrl = this.randomAvatar()
            // 设置管理员身份
            this.admin.permission = 'admin'
            // 设置Token
            this.admin.token = this.uuid()
            const { data } = await add(this.admin)
            if (data.result === true) {
              this.admin.id = data.id
            }
            this.adminList.push(this.admin)
          }

          const { adminName, realName, remark } = this.admin
          this.dialogVisible = false
          this.$notify({
            title: isEdit ? '修改成功' : '添加成功',
            dangerouslyUseHTMLString: true,
            message: `
            <div>账号: ${adminName}</div>
            <div>真实姓名: ${realName}</div>
            <div>备注: ${remark}</div>
          `,
            type: 'success'
          })
        } else {
          console.log('error submit!!')
          return false
        }
      })
    },
    // 时间戳转日期
    timestampToTime(timestamp) {
      var date = new Date(timestamp);   //创建一个指定的日期对象
      var year = date.getFullYear();  //取得4位数的年份
      var month = date.getMonth() + 1;  //取得日期中的月份，其中0表示1月，11表示12月
      var day = date.getDate();      //返回日期月份中的天数（1到31）
      var hour = date.getHours();     //返回日期中的小时数（0到23）
      var minute = date.getMinutes(); //返回日期中的分钟数（0到59）
      var second = date.getSeconds(); //返回日期中的秒数（0到59）
      if (month < 10) {
        month = '0' + month;
      }
      if (day < 10) {
        day = '0' + day;
      }
      if (hour < 10) {
        hour = '0' + hour;
      }
      if (minute < 10) {
        minute = '0' + minute;
      }
      if (second < 10) {
        second = '0' + second;
      }
      return year + "-" + month + "-" + day + " " + hour + ":" + minute + ":" + second;
    },
    randomAvatar() {
      const random = Math.floor(Math.random() * 5)// 0~4
      return this.avatarList[random]
    },
    uuid() {
      return ([1e7] + -1e3 + -4e3 + -8e3 + -1e11).replace(/[018]/g, c =>
        (c ^ crypto.getRandomValues(new Uint8Array(1))[0] & 15 >> c / 4).toString(16)
      )
    }
  }
}
</script>

<style lang="scss" scoped>
.app-container {
  .roles-table {
    margin-top: 30px;
  }
  .permission-tree {
    margin-bottom: 30px;
  }
}
</style>
